package cn.tedu.jxc.service.impl;

import cn.tedu.jxc.ex.ServiceException;
import cn.tedu.jxc.mapper.CategoryMapper;
import cn.tedu.jxc.mapper.ProductMapper;
import cn.tedu.jxc.pojo.dto.ProductDTO;
import cn.tedu.jxc.pojo.entity.Product;
import cn.tedu.jxc.pojo.vo.CategoryStandardVO;
import cn.tedu.jxc.pojo.vo.ProductListItemVO;
import cn.tedu.jxc.service.ProductService;
import cn.tedu.jxc.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<ProductListItemVO> list() {
        log.debug("查询商品列表成功!");
        return productMapper.getList();
    }

    @Override
    public void addNew(ProductDTO productDTO) {
        CategoryStandardVO categoryStandardVO = categoryMapper.selectById(productDTO.getCategoryId());
        if (categoryStandardVO == null) {
            String message="添加失败,类别不存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        if (categoryStandardVO.getIsParent()!=0){
            String message="添加失败,类别不能包含子类别!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        Product product = new Product();
        BeanUtils.copyProperties(productDTO,product);
        int rows = productMapper.insert(productDTO);
        if (rows!=1){
            String message ="新增失败,服务器忙,稍后再试!";
            log.debug(message);
            throw  new ServiceException(ServiceCode.ERR_CONFLICT,message );
        }
        log.debug("商品添加成功!");
    }
}
